package com.lin.activity;

import org.json.JSONException;
import org.json.JSONObject;

import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.SharePreferenceUtil;
import com.lin.utils.Utils;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.utils.JsonUtils;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.LoginActivity;
import com.yunfeng.supercall.activity.MainActivity;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.service.CallConnectionService;
import com.yunfeng.supercall.service.HandlePhoneDataIntentService;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

public class LauncherActivity extends BaseActivity {
	public HttpClient mHttpClient = new HttpClient();
	private String phone;
	private String pass;
	Session mSession;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_launcher);
		
		mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		
		if(!TextUtils.isEmpty(SharePreferenceUtil.getInstance().getUserName(getApplicationContext()))) {
			startService(new Intent(this, HandlePhoneDataIntentService.class));
			phone = SharePreferenceUtil.getInstance().getUserName(getApplicationContext());
			pass = SharePreferenceUtil.getInstance().getPassword(getApplicationContext());
			Thread thread = new Thread(runnable);
			thread.setPriority(9);
			thread.start();
			
		} else {
			startActivity(new Intent(LauncherActivity.this,
					LoginActivity.class));
			finish();
		}
	}
	
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			mHandler.sendEmptyMessage(0);
		}
		
	};
	
	
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			login();
		}
		
	};
	
	private void login() {
		
		mSession.getUserLogin2(getApplicationContext(), phone, pass, new ResultReceiver<String>(){

			@Override
			public void onResult(boolean last, String data) {
				// TODO Auto-generated method stub
				if(data != null) { //有网络情况下
					startService(new Intent(LauncherActivity.this, HandlePhoneDataIntentService.class));
					SharePreferenceUtil.getInstance().updateUserInfo(LauncherActivity.this, phone, pass);
					cancelProgressDialog();

					SharePreferenceUtil.getInstance().saveUserInfo(getApplicationContext(), data);
					UserBean mUser = JsonUtils.parse(
							data.substring(1, data.length() - 1), UserBean.class);
					mUser.setPassword(pass);
					getLoginManager(getActivity()).saveUser(mUser);
					startService(new Intent(LauncherActivity.this,
							CallConnectionService.class).putExtra("code",
									mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
					// startActivity(new Intent(LoginActivity.this,
					// MainActivity.class));
					
					
					if (getIntent().getBooleanExtra(KEY_DATA, true)) {
						showToast(R.string.login_success);
						startActivity(new Intent(LauncherActivity.this,
								MainActivity.class));

						finish();
						ManagerFactory.clearAll();
					} else {
						setResult(RESULT_OK, new Intent().putExtra(KEY_DATA, true));
						finish();
					}
				} else {
					cancelProgressDialog();
					String result = SharePreferenceUtil.getInstance().getUserInfo(getApplicationContext());
					if(!TextUtils.isEmpty(result)) {
						UserBean mUser = JsonUtils.parse(
								result.substring(1, result.length() - 1), UserBean.class);
						mUser.setPassword(pass);
						getLoginManager(getActivity()).saveUser(mUser);
						startService(new Intent(LauncherActivity.this,
								CallConnectionService.class).putExtra("code",
										mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
						// startActivity(new Intent(LoginActivity.this,
						// MainActivity.class));
						if (getIntent().getBooleanExtra(KEY_DATA, true)) {
							showToast(R.string.login_success);
							startService(new Intent(LauncherActivity.this, HandlePhoneDataIntentService.class));
							startActivity(new Intent(LauncherActivity.this,
									MainActivity.class));

							finish();
							ManagerFactory.clearAll();
						}	
					} else {
						showToast("请确保网络并输入正确账号密码");
						startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
					}
				}
			}

		});
		/*JSONObject json = getBaseParams(this);
		try {
			json.put(Constants.KEY_PHONE, phone);
			json.put(Constants.KEY_PASS, pass);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(Constants.FUNCTION_LOGIN, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				startActivity(new Intent(LauncherActivity.this,
						LoginActivity.class));
				finish();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub

				UserBean mUser = JsonUtils.parse(
						data.substring(1, data.length() - 1), UserBean.class);
				mUser.setPassword(pass);
				BaseActivity.getLoginManager(LauncherActivity.this).saveUser(mUser);
				startService(new Intent(LauncherActivity.this,
						CallConnectionService.class).putExtra("code",
								mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
				if (getIntent().getBooleanExtra(Constants.KEY_DATA, true)) {
					 startActivity(new Intent(LauncherActivity.this,
					 MainActivity.class));
					finish();
					ManagerFactory.clearAll();
				} else {
					setResult(RESULT_OK, new Intent().putExtra(Constants.KEY_DATA, true));
					finish();
				}
			}
		});*/
	}
	
	/**
	 * 获取基础的参数
	 * 
	 * @param context
	 * @return
	 */
	public static JSONObject getBaseParams(Context context) {
		JSONObject json = new JSONObject();
		try {
			UserBean u = getUser(context);
			if (u == null) {
				json.put("i_userid", 0);
			} else {
				json.put("i_userid", getUser(context).getUserid());
			}

			json.put("i_lng", AppContext.lng);
			json.put("i_lat", AppContext.lat);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}
	
}